package com.rogue.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.cglib.CglibUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rogue.common.core.constant.CommonResultCode;
import com.rogue.common.core.utils.ResultDTO;
import com.rogue.domain.entity.HsDepartment;
import com.rogue.feign.EmployeeFeign;
import com.rogue.system.domain.dto.UserDTO;
import com.rogue.system.domain.dto.UserPageDTO;
import com.rogue.system.domain.entity.SysRole;
import com.rogue.system.domain.entity.SysUser;
import com.rogue.system.domain.entity.SysUserRole;
import com.rogue.system.domain.vo.UserRoleVo;
import com.rogue.system.domain.vo.UserVo;
import com.rogue.system.mapper.SysRoleMapper;
import com.rogue.system.mapper.SysRoleMenuMapper;
import com.rogue.system.mapper.SysUserMapper;
import com.rogue.system.mapper.SysUserRoleMapper;
import com.rogue.system.service.SysUserService;
import java.util.Objects;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;

/**
* @author Yeah
* @description 针对表【sys_user(用户表)】的数据库操作Service实现
* @createDate 2022-03-16 14:23:08
*/
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
    implements SysUserService {

    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysRoleMenuMapper sysRoleMenuMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private SysUserMapper sysUserMapper;

    // 跨服务调用 应该要使用 openfeign
    @Resource
    private EmployeeFeign departmentMapper;


    @Override
    public Boolean createUserAndRole(UserDTO userDTO) {
        final Long roleId = sysRoleMapper.findRoleByName(userDTO.getRoleName());
        final SysUser sysUser = new SysUser();
        BeanUtil.copyProperties(userDTO,sysUser);
        final boolean save = this.save(sysUser);
        final int insert = sysUserRoleMapper.insert(
            SysUserRole.builder().roleId(roleId).userId(sysUser.getId()).build());
        if (save && (insert > 0)){
            return true;
        }
        return false;
    }

    @Override
    public Boolean removeUserAndRole(Long id) {
        SysUserRole sysUserRole = sysUserRoleMapper.selectOne(
            new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId, id));
        Assert.notNull(sysUserRole,"用户不存在!");
        sysUserRoleMapper.deleteById(sysUserRole.getId());
        return this.baseMapper.deleteById(id) > 0;
    }

    @Override
    public Boolean lockUserById(Long id) {
        // 检查用户是否存在
        SysUser sysUser = this.baseMapper.selectById(id);
        Assert.notNull(sysUser,"用户不存在!");

        int flag = this.baseMapper.update(sysUser,
            new UpdateWrapper<SysUser>().lambda().set(SysUser::getLockStatus, CommonResultCode.LOCK).eq(SysUser::getId,id));
        return flag > 0;

    }

    @Override
    public Boolean unlockUserById(Long id) {
        // 检查用户是否存在
        SysUser sysUser = this.baseMapper.selectById(id);
        Assert.notNull(sysUser,"用户不存在!");

        int flag = this.baseMapper.update(sysUser,
            new UpdateWrapper<SysUser>().lambda().set(SysUser::getLockStatus,
                CommonResultCode.UNLOCK).eq(SysUser::getId,id));
        return flag > 0;
    }

    @Override
    public Boolean recoverUser(Long id) {

        // 检查用户是否存在
        // SysUser sysUser = this.baseMapper.selectOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getId,id).eq(SysUser::getDeleted,CommonResultCode.DELETE));
        // Assert.notNull(sysUser,"用户不存在!");

        // 恢复用户
        SysUser sysUser = new SysUser();
        sysUser.setId(id);
        int flag = this.baseMapper.update(sysUser,
            new UpdateWrapper<SysUser>().lambda().set(SysUser::getDeleted, CommonResultCode.RECOVER).eq(SysUser::getId,id));
        // 恢复用户的角色权限
        // SysUserRole sysUserRole = sysUserRoleMapper.selectOne(
        //     new UpdateWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId, id));
        // SysUserRole sysUserRole = new SysUserRole();
        // sysUserRole.setUserId(id);
        int update = sysUserRoleMapper.update(null, new UpdateWrapper<SysUserRole>().lambda()
            .set(SysUserRole::getDeleted, CommonResultCode.RECOVER).eq(SysUserRole::getUserId,id));
        return (update > 0 && flag > 0);

    }


    @Override
    public PageInfo<UserVo> listPageUser(UserPageDTO userPageDTO) {
        // 分页查询
        System.out.println(userPageDTO);
        PageInfo<UserVo> pageInfo = PageHelper.startPage(userPageDTO.getPage(),
                userPageDTO.getCount())
            .doSelectPageInfo(() -> sysUserMapper.selectList(new QueryWrapper<SysUser>().lambda()
            .like(StrUtil.isNotBlank(userPageDTO.getNickname()),SysUser::getNiceName,userPageDTO.getNickname())
            .eq(Objects.nonNull(userPageDTO.getDeptId()),SysUser::getDeptId,userPageDTO.getDeptId())
            .eq(Objects.nonNull(userPageDTO.getGender()), SysUser::getSex,userPageDTO.getGender())
            .eq(Objects.nonNull(userPageDTO.getLockStatus()),SysUser::getLockStatus,userPageDTO.getLockStatus())));
                // .select(SysUser::getId, SysUser::getDeptId, SysUser::getNiceName, SysUser::getSex,
                //     SysUser::getLockStatus)));
        // 调用了 CglibUtil 来进行列表类的转换
        pageInfo.setList(CglibUtil.copyList(pageInfo.getList(), UserVo::new));
        pageInfo.getList().stream().forEach(x ->{
            ResultDTO<HsDepartment> hsDepartment = departmentMapper.easyGetOneDept(x.getDeptId());
            if (Objects.nonNull(hsDepartment)){
                x.setDeptName(hsDepartment.getData().getName());
            }
        });

        return pageInfo;
    }

    @Override
    public UserRoleVo getUserAndRole(Long id) {
        UserRoleVo userRoleVo = new UserRoleVo();
        SysUser sysUser = this.baseMapper.selectById(id);
        userRoleVo.setUsername(sysUser.getUserName());
        SysUserRole sysUserRole = sysUserRoleMapper.selectOne(
            new QueryWrapper<SysUserRole>().eq("user_id", sysUser.getId()));
        SysRole sysRole = sysRoleMapper.selectById(sysUserRole.getRoleId());
        userRoleVo.setRoleName(sysRole.getRoleName());
        return userRoleVo;
    }

    @Override
    public UserRoleVo getUserAndRoleByName(String name) {
        UserRoleVo userRoleVo = new UserRoleVo();
        SysUser sysUser = this.baseMapper.selectOne(new QueryWrapper<SysUser>().eq("user_name",name));
        userRoleVo.setUsername(sysUser.getUserName());
        SysUserRole sysUserRole = sysUserRoleMapper.selectOne(
                new QueryWrapper<SysUserRole>().eq("user_id", sysUser.getId()));
        SysRole sysRole = sysRoleMapper.selectById(sysUserRole.getRoleId());
        userRoleVo.setRoleName(sysRole.getRoleName());
        return userRoleVo;

    }


}




